#pragma once
#include "Socket.hpp"
#include <iostream>
#include <signal.h>
#include <functional>
using namespace std;
using func_t = std::function<std::string(std::string &package)>;
class Tcpserver
{
public:
    Tcpserver(uint16_t &port, func_t callback) : port_(port), callback_(callback)
    {
    }
    void ServerInit()
    {
        socket.Socket();
        socket.Bind(port_);
        socket.Listen();
        cout << "server init success" << endl;
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = socket.Accept(clientip, clientport);
            if (sockfd < 0)
                continue;
            lg(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);

            if (fork() == 0)
            {
                socket.Close();

                while (true)
                {
                    string in_buffer;
                    char buffer[1024];
                    // 提供服务  接收客户端消息
                    ssize_t s = read(sockfd, buffer, sizeof(buffer));

                    if (s > 0)
                    {
                        buffer[s] = 0;
                        in_buffer += buffer;
                        lg(Debug, "debug:\n%s", in_buffer.c_str()); // 打印封装后的序列化消息
                                                                    // while (true)
                                                                    // {
                        string info = callback_(in_buffer);         // 处理客户端消息

                        // if (info.empty())
                        //     break;

                        int n = write(sockfd, info.c_str(), info.size());
                        //}
                    }
                    else if (s == 0)
                    {

                        break;
                    }
                    else
                    {
                        cout << "read fail" << endl;
                        break;
                    }
                }
                exit(0);
            }
            close(sockfd);
        }
    }
    ~Tcpserver()
    {
    }

private:
    uint16_t port_;
    Sock socket;
    func_t callback_;
};